package com.lzx.iteam.net;

import android.os.Message;
import com.lzx.iteam.bean.SalaryBaseBean;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by xuepengju on 14-3-20.
 */
public class GetSalaryDataMsg extends CcMsgStructure {

    private Message mCallback;

    public GetSalaryDataMsg(Message callback){
        mCallback = callback;
    }

    @Override
    public void onReceive(JSONObject data) {
        ArrayList<SalaryBaseBean> mDatas = new ArrayList<>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
//            mDatas = fromJsonList(jsonObject.getString("members"), SalaryBaseBean.class);
            JSONArray array = jsonObject.getJSONArray("members");
            for (int i = 0; i < array.length(); i++) {
                SalaryBaseBean bean = new SalaryBaseBean();
                JSONObject obj = array.getJSONObject(i);
                bean.set_id(obj.getString("_id"));
                bean.setUser_name(obj.getString("user_name"));
                if (obj.has("pension_base")){
                    bean.setPension_base(Float.parseFloat(obj.getString("pension_base")));
                }else{
                    bean.setPension_base(-1);
                }
                if (obj.has("medical_base")){
                    bean.setMedical_base(Float.parseFloat(obj.getString("medical_base")));
                }else{
                    bean.setMedical_base(-1);
                }
                if (obj.has("provident_fund_base")){
                    bean.setProvident_fund_base(Float.parseFloat(obj.getString("provident_fund_base")));
                }else{
                    bean.setProvident_fund_base(-1);
                }
                mDatas.add(bean);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (mCallback != null)
        {
            mCallback.obj = mDatas;
            mCallback.arg1 = 0;
            mCallback.sendToTarget();
            return;
        }
    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if(mCallback != null){
            mCallback.arg1 = error;
            if(!StringUtil.isEmpty(errorMsg)){
                mCallback.obj = errorMsg;
            }else{
                mCallback.obj = Constants.NETWORK_WRROR;
            }
            mCallback.sendToTarget();
        }
    }
}
